package com.pms.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 楼层管理界面接口
 * 1） 楼层删除时，删除 当前楼层及以上的楼层，需判断是否 有会员认证房屋
 * 2)  楼层 不提供修改功能
 * </p>
 *
 * @author ASUS_B
 * @since 2017-10-24
 */
@RestController
@RequestMapping("/unitFloorBase")
@Api(value = "楼层管理界面接口", description = "楼层管理界面接口")
public class UnitFloorController extends BaseController {
    @Autowired
    private IUnitHouseService unitHouseService;
    @Autowired
    private IEstateAgencyService agencyService;
    @Autowired
    private IUnitBuildingService unitBuildingService;
    @Autowired
    private IUnitFloorService unitFloorService;
    @Autowired
    private IHouseMasterInfoService houseMasterInfoService;
    @Autowired
    IChargeTemplateService chargeTemplateService;

    @ApiOperation(value = "添加楼层(单元/楼层id需有一个)")
    @RequestMapping(value = "/addFloor", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "floorId", value = "楼层id(用于查询单元id,以单元id为准，有值可不传单元id)", required = false, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "unitId", value = "单元id(有值可不传楼层id)", required = false, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "addFloorNum", value = "楼层添加数量(默认为1)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "isShowApp", value = "app是否显示(1-显示(默认)，2-不显示)", required = false, dataType = "int", paramType = "form"),
    })
    public R addFloor(Long floorId, Long unitId, Integer addFloorNum, Integer isShowApp) {
        Long communityId = null;
        Long agencyId = null;
        if (null == unitId) {
            if (null == floorId) {
                return R.error(400, "信息不全,无法添加楼层");
            }
            if (null != floorId) {
                UnitFloor floor = unitFloorService.selectById(floorId);
                if (null == floor) {
                    return R.error(400, "信息不全,无法添加楼层");
                }
                unitId = floor.getUnitId();
            }
        }
        if (null != unitId) {
            UnitBuilding unit = unitBuildingService.selectById(unitId);
            parameterIsNull(unit, "暂无该单元信息");
            communityId = unit.getCommunityId();
            agencyId = unit.getAgencyId();
        }
        if (null == communityId) {
            return R.error(400, "信息不全,无法添加楼层");
        }
        int floorCount = unitFloorService.selectCount(new EntityWrapper<UnitFloor>().eq("unit_id", unitId));
        if (null == addFloorNum || addFloorNum < 1) {
            addFloorNum = 1;
        }
        if (null == isShowApp || isShowApp != 2) {
            isShowApp = 1;
        }
        List<UnitFloor> addList = new ArrayList<UnitFloor>();
        for (int x = 1; x <= addFloorNum; x++) {
            UnitFloor floor = new UnitFloor();
            floor.setFloorName((floorCount + x) + "楼");
            floor.setCommunityId(communityId);
            floor.setUnitId(unitId);
            floor.setIsShowApp(isShowApp);
            floor.setAgencyId(agencyId);
            floor.setFloorSort(floorCount + x);
            addList.add(floor);
        }
        unitFloorService.insertBatch(addList);
        // 同步清除 查询单元楼层户室的缓存
        unitFloorService.clearPreKeyCache("unitHouse:selectUnitFloorHouse");
        return R.ok();
    }


    @ApiOperation(value = "删除楼层")
    @RequestMapping(value = "/delFloor", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "floorId", value = "楼层id", required = true, dataType = "long", paramType = "form"),
    })
    public R delFloor(Long floorId) {
        parameterIsNull(floorId, "请选择要删除的楼层");
        UnitFloor delFloor = unitFloorService.selectById(floorId);
        parameterIsNull(delFloor, "该楼层信息已不存在");
        int countUnitFloorNum = unitFloorService.selectCount(new EntityWrapper<UnitFloor>().eq("unit_id", delFloor.getUnitId()));
        if (delFloor.getFloorSort() < countUnitFloorNum) {
            return R.error(400, "该楼层不属于顶层,请从该单元顶层楼层开始删除");
        }
        int countFloorTwoHouStateNum = unitHouseService.selectCount(new EntityWrapper<UnitHouse>().eq("floor_id", floorId).eq("is_have_member", 2));
        if (countFloorTwoHouStateNum > 0) {
            return R.error(400, "该楼层的户室尚有会员认证,无法删除");
        }
        unitHouseService.delete(new EntityWrapper<UnitHouse>().eq("floor_id", floorId));
        houseMasterInfoService.delete(new EntityWrapper<HouseMasterInfo>().eq("floor_id", floorId));
        unitFloorService.deleteById(floorId);
        // 同步清除 查询单元楼层户室的缓存
        unitFloorService.clearPreKeyCache("unitHouse:selectUnitFloorHouse");
        return R.ok();
    }

    @ApiOperation(value = "改变楼层是否在app端显示")
    @RequestMapping(value = "/changeIsShowApp", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "floorId", value = "楼层id", required = true, dataType = "long", paramType = "form"),
    })
    public R changeIsShowApp(Long floorId) {
        parameterIsNull(floorId, "楼层id不能为空");
        UnitFloor unitFloor = unitFloorService.selectById(floorId);
        parameterIsNull(unitFloor, "没有该楼层信息");
        if (null == unitFloor.getIsShowApp() || 1 == unitFloor.getIsShowApp()) {
            unitFloor.setIsShowApp(2);
        } else {
            unitFloor.setIsShowApp(1);
        }
        unitFloorService.updateById(unitFloor);
        // 同步清除 查询单元楼层户室的缓存
        unitFloorService.clearPreKeyCache("unitHouse:selectUnitFloorHouse");
        return R.ok();
    }


    @ApiOperation(value = "分页查询楼层")
    @RequestMapping(value = "/readPage", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "请求条数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageNum", value = "请求页数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "communityId", value = "社区id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name="agencyId",value="物业机构id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name = "unitId", value = "单元id", required = false, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "isShowApp", value = "app是否显示(1-显示，2-不显示,3-所有(默认))", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sortBy", value = "排序显示(1-降序显示(默认),2-升序显示)", required = false, dataType = "int", paramType = "form"),
    })
    public R readPage(Integer pageSize, Integer pageNum, Long communityId, Long unitId, Integer isShowApp, Integer sortBy, Long agencyId) {
        parameterIsNull(agencyId, "物业机构id不能为空");
        if (null == pageNum || pageNum < 1) {
            pageNum = 1;
        }
        if (null == pageSize || pageSize < 1) {
            pageSize = 10;
        }
        Page<UnitFloor> page = new Page<UnitFloor>(pageNum, pageSize);
        Wrapper<UnitFloor> wrapper = new EntityWrapper<UnitFloor>();
        if(null!=agencyId){
            wrapper.eq("agency_id",agencyId);
        }
        if(null!=communityId){
            wrapper.eq("community_id", communityId);
        }
        if (null != isShowApp) {
            if (isShowApp == 2 || isShowApp == 1) {
                wrapper.eq("is_show_app", isShowApp);
            }
        }
        if (null != unitId) {
            wrapper.eq("unit_id", unitId);
        }
        /* ====排序=====*/
        wrapper.orderBy("community_id", false);//默认根据 社区id 降序排序
        wrapper.orderBy("unit_id", false);//默认根据 单元id 降序排序
        if (null == sortBy || sortBy != 2) {
            sortBy = 1;
        }//默认根据 序号 降序排序
        if (sortBy == 1) {
            wrapper.orderBy("floor_sort", false);
        }
        if (sortBy == 2) {
            wrapper.orderBy("floor_sort", true);
        }
        Page<UnitFloor> returnPage = unitFloorService.selectPage(page, wrapper);
        return R.ok().put("data", returnPage).putMpPageDescription().putDescription(UnitFloor.class);
    }

    @ApiOperation(value = "查询单元下级楼层")
    @RequestMapping(value = "/readList", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "unitId", value = "单元id", required = true, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "isShowApp", value = "app是否显示(1-显示(默认)，2-不显示,3-所有(默认))", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sortBy", value = "排序显示(1-降序显示(默认),2-升序显示)", required = false, dataType = "int", paramType = "form"),
    })
    public R readList(Long unitId, Integer isShowApp, Integer sortBy) {
        parameterIsNull(unitId, "单元id不能为空");
        Wrapper<UnitFloor> wrapper = new EntityWrapper<UnitFloor>();
        wrapper.eq("unit_id", unitId);
        if (null != isShowApp) {
            if (isShowApp == 1 || isShowApp == 2) {
                wrapper.eq("is_show_app", isShowApp);
            }
        }
        if (null == sortBy || sortBy != 2) {
            sortBy = 1;
        }//默认根据 序号 降序排序
        if (sortBy == 1) {
            wrapper.orderBy("floor_sort", false);
        }
        if (sortBy == 2) {
            wrapper.orderBy("floor_sort", true);
        }
        List<UnitFloor> floorList = unitFloorService.selectList(wrapper);
        if (null == floorList) {
            floorList = new ArrayList<UnitFloor>();
        }
        return R.ok().put("data", floorList).putDescription(UnitFloor.class);
    }

    @ApiOperation(value = "楼层批量绑定物业费模板(覆盖原来的)")
    @RequestMapping(value = "/bingChargeTemplateToHouseByFloorId",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="floorId",value="楼层id",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="chargeTemplateId",value="物业费模板id",required = true,dataType = "Long",paramType="form"),
    })
    public R bingChargeTemplateToHouseByFloorId(Long floorId,Long chargeTemplateId){
        parameterIsNull(floorId,"请选择楼层");
        UnitFloor unit = unitFloorService.selectById(floorId);
        parameterIsNull(unit,"没有该楼层信息");
        parameterIsNull(chargeTemplateId,"请选择物业费模板");
        ChargeTemplate chargeTemplate =chargeTemplateService.selectById(chargeTemplateId);
        parameterIsNull(chargeTemplate,"没有该物业费模板信息");
        List<UnitHouse> unitHouses = unitHouseService.selectList(new EntityWrapper<UnitHouse>().eq("floor_id",floorId));
        if(null!=unitHouses&&!unitHouses.isEmpty()){
            for(int x=0;x<unitHouses.size();x++){
                unitHouses.get(x).setChargeTemplateId(chargeTemplateId);
                unitHouses.get(x).setChargeTemplateName(chargeTemplate.getChargeTemplateName());
                unitHouses.get(x).setIsHavaChargeTemplate(1);
            }
            unitHouseService.updateBatchById(unitHouses);
        }
        return R.ok();
    }
}
